#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "../Sock/errno.hpp"
#include "../Sock/Logmessage.hpp"

namespace Client
{
    using namespace std;
    class udpClient
    {
    public:
        udpClient(const string &serverip, const uint16_t &serverport)
            : serverip_(serverip), serverport_(serverport), sockfd_(-1)
        {}
        void initClient()
        {
            //****1.创建UDP网络通信端口****
            sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
            if (sockfd_ == -1)
            {
                logMessage(FATAL,"socket err ");
                exit(SOCKET_ERR);
            }
        }

        void run()
        {
            struct sockaddr_in server; // 目的Ip+port
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            // 主机序列转网络序列
            server.sin_addr.s_addr = inet_addr(serverip_.c_str());
            server.sin_port = htons(serverport_);

            string message;

            while (true)
            {
                getline(cin, message);
                message[message.size()]=0;
                sendto(sockfd_, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));

                char buffer[1024];
                struct sockaddr_in server;
                socklen_t len=sizeof(server);
                size_t n = recvfrom(sockfd_, buffer, sizeof(buffer) - 1, 0,(struct sockaddr*)&server,&len);
                if (n > 0)
                    buffer[n] = 0;
                else { break;}    
                std::cout << buffer << std::endl;
            }
        }
        ~udpClient(){}

    private:
        int sockfd_;
        string serverip_;
        uint16_t serverport_;
    };
}
